<template>
  <!--  收文、发文 已归档列表 -->
  <div ref="contentRef" class="content">
    <!-- 筛选 -->
    <div class="top-tool">
      <!-- 时间&状态 -->
      <div class="tool-left">
        <DatePicker
          ref="datePicker"
          @changeBeginTime="changeBeginTime"
          @changeEndTime="changeEndTime"
        ></DatePicker>
        <!-- <a-select
          v-model:value="typeValue"
          style="width: 160px; border-radius: 4px"
          placeholder="类型"
        >
          <template #suffixIcon>
            <svg-icon icon-class="icon_select_down" class-name="icon-select-down"></svg-icon>
          </template>
          <a-select-option v-for="(item, i) in typeArr" :key="i" :value="item.value">{{
            item.text
          }}</a-select-option>
        </a-select> -->
        <a-select
          v-model:value="stateValue"
          style="width: 160px; border-radius: 4px"
          placeholder="状态"
        >
          <template #suffixIcon>
            <svg-icon icon-class="icon_select_down" class-name="icon-select-down"></svg-icon>
          </template>
          <a-select-option v-for="(item, i) in stateArr" :key="i" :value="item.value">{{
            item.text
          }}</a-select-option>
        </a-select>
      </div>
      <!-- 搜索&重置 -->
      <div class="tool-right">
        <a-input-group compact>
          <a-select v-model:value="searchTitle">
            <template #suffixIcon>
              <svg-icon icon-class="icon_select_down" class-name="icon-select-down"></svg-icon>
            </template>
            <a-select-option v-for="(item, i) in searchTitleArr" :key="i" :value="item.value">{{
              item.text
            }}</a-select-option>
          </a-select>
          <a-input
            v-model:value="keyword"
            style="width: 200px; height: 36px; border-radius: 0 4px 4px 0; margin-right: 8px"
            placeholder="请输入关键字查询"
          >
            <template #prefix>
              <svg-icon icon-class="icon_search" class-name="icon-search"></svg-icon>
            </template>
          </a-input>
        </a-input-group>
        <a-button type="primary" @click="searchBtnClick">搜索</a-button>
        <a-button @click="resetBtnClick">重置</a-button>
      </div>
    </div>
    <!-- 批量操作 -->
    <!-- <div class="center-tool">
      <div
        v-for="(item, i) in batchBtnsArr"
        :key="i"
        :class="['center-tool-btn', selectedRowKeys.length > 0 ? 'btn-active' : '']"
        @click="batchBtnClick(i)"
      >
        <svg-icon :icon-class="item.svgName" :class-name="item.className"></svg-icon>
        <span>{{ item.btnName }}</span>
      </div>
    </div> -->
    <!-- 表格  -->
    <div class="table-bg">
      <!-- 表格 -->
      <!-- :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }" -->
      <a-table
        :columns="columns"
        :data-source="dataSource"
        bordered
        loading="false"
        :pagination="false"
        table-layout="fixed"
      >
        <template #bodyCell="{ column, text, record }">
          <a-tooltip
            v-if="column.dataIndex !== 'operation'"
            :get-popup-container="() => contentRef"
            placement="top"
            :title="
              column.dataIndex === 'documentTitle'
                ? text?.length > 19
                  ? text
                  : ''
                : column.dataIndex === 'documentNum'
                ? text?.length > 13
                  ? text
                  : ''
                : column.dataIndex === 'handler'
                ? text?.length > 7
                  ? text
                  : ''
                : ''
            "
          >
            <div>
              <span v-if="column.dataIndex === 'processStatus'" class="state-bg">
                <svg-icon
                  :icon-class="stateIcons[parseInt(text ? text : '')]"
                  class-name="icon-state"
                />
                <span class="state-text">{{ stateTexts[parseInt(text ? text : '')] }}</span>
              </span>
              <span v-else>{{ text ? text : '--' }}</span>
            </div>
          </a-tooltip>
          <div v-else class="editable-row-operations">
            <span v-if="optionBtns.indexOf('查看') !== -1" style="margin-right: 12px">
              <a class="operation-normal" @click="gotoDetail(record)">详情</a>
            </span>
            <span v-if="record.processStatus * 1 === 1">
              <a
                v-if="optionBtns.indexOf('归档') !== -1"
                style="margin-right: 12px"
                class="operation-normal"
                @click="showModal(record.id)"
                >归档</a
              >
              <span
                v-if="optionBtns.indexOf('删除') !== -1"
                class="operation-normals"
                @click="deleteRecord(record.id)"
                >删除</span
              >
            </span>
            <span
              v-else-if="
                record.processStatus * 1 === 2 ||
                record.processStatus * 1 === 5 ||
                record.processStatus * 1 === 6
              "
            >
              <span
                v-if="optionBtns.indexOf('删除') !== -1"
                class="operation-normals"
                @click="deleteRecord(record.id)"
                >删除</span
              >
            </span>
            <span
              v-else-if="record.processStatus * 1 === 0 && optionBtns.indexOf('废弃') !== -1"
              class="operation-normals"
              @click="discardRecord(record.processInstanceId)"
              >废弃</span
            >
          </div>
        </template>
      </a-table>
      <!-- 分页器 -->
      <div v-show="dataSource.length > 0 && total > 10" class="pagination-bar">
        <div class="pagination-box">
          <a-pagination
            :current="currentPage"
            :page-size="pageSize"
            :total="total"
            :show-total="total => `共${total}条`"
            :show-size-changer="true"
            @change="onPageChange"
          />
          <div class="change-page-bg">
            <span>前往</span>
            <input
              class="change-page-input"
              type="text"
              @keyup="changePageKeyUp"
              @blur="changePageBlur"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
  <ArchivedModal
    v-if="showArchivedModal"
    :tags="archivedLabelArr"
    @on-modal-dismiss="archivedModalDismiss"
    @on-modal-make-sure="archivedModalMakeSure"
  />
  <DiscardModal
    v-if="showDiscardRecordModal"
    @on-modal-dismiss="discardModalDismiss"
    @on-modal-make-sure="discardModalMakeSure"
  />
  <MyModal
    :modal-style="'iconStyle'"
    :show-icon="true"
    :visible="showDeleteRecordModal"
    :options="deleteRecordOptions"
  ></MyModal>
</template>
<script setup>
import { ref, onMounted, onUpdated } from 'vue';
import { useRouter } from 'vue-router';
import ArchivedModal from '../archiveModal/index.vue';
import DiscardModal from '../discardModal/index.vue';
import DatePicker from '@/components/datePicker/index.vue';
import MyModal from '@/components/formPageDialog';
import { Interface } from '@/api/library/library.js';
import { message } from 'ant-design-vue';
import { changeData } from '@/utils/validate.js';
import store from '../../../../store';
let datePicker = ref(null);
const isLoading = ref(false);
const contentRef = ref(null);
// ------------- 筛选 -------------
const beginTime = ref('');
const endTime = ref('');
const isClearDate = ref(false);
function changeBeginTime(newBeginTime) {
  // console.log('接收到数据newBeginTime：', newBeginTime);
  beginTime.value = newBeginTime;
}
function changeEndTime(newEndTime) {
  // console.log('接收到数据newEndTime：', newEndTime);
  endTime.value = newEndTime;
}
// const typeValue = ref();
// const typeArr = ref([
//   { value: '0', text: '发文' },
//   { value: '1', text: '收文' }
// ]);
const stateValue = ref();
const stateArr = ref([
  { value: 'all', text: '全部' },
  { value: '0', text: '办理中' },
  { value: '1', text: '已办结' },
  { value: '2', text: '已撤销' },
  // { value: '3', text: '已驳回' },
  // { value: '4', text: '已归档' },
  { value: '5', text: '已废弃' },
  { value: '6', text: '已拒绝' }
]);

const searchTitle = ref('title');
const searchTitleArr = ref([
  { value: 'title', text: '标题' },
  { value: 'number', text: '文号' },
  { value: 'handler', text: '处理人' }
]);
const keyword = ref('');
function searchBtnClick() {
  currentPage.value = 1;
  getDataList();
}
function resetBtnClick() {
  currentPage.value = 1;
  isClearDate.value = false;
  isClearDate.value = true;
  stateValue.value = null;
  searchTitle.value = 'title';
  keyword.value = '';
  beginTime.value = '';
  endTime.value = '';
  datePicker.value.resetTimes(); // 清除子组件时间
  getDataList();
}
// ------------- table -------------
const columns = ref([
  {
    title: '标题',
    dataIndex: 'documentTitle',
    width: '312px'
  },
  {
    title: '文号',
    dataIndex: 'documentNum',
    width: '195px'
  },
  {
    title: '类型',
    dataIndex: 'documentType',
    width: '85px'
  },
  {
    title: '状态',
    dataIndex: 'processStatus',
    width: '113px'
  },
  {
    title: '处理人',
    dataIndex: 'handler',
    width: '145px'
    // tooltip更改 100px
  },
  {
    title: '收文日期',
    dataIndex: 'receivedDate',
    width: '134px'
  },

  {
    title: '操作',
    dataIndex: 'operation'
  }
]);
// 0办理中 1已办结 2已撤销 3已驳回 4已归档 5已废弃 6已拒绝
const stateIcons = ref([
  'form_icon_banlizhong',
  'form_icon_yibanjie',
  'form_icon_yichexiao',
  'form_icon_yibohui',
  'form_icon_yibanjie',
  'form_icon_yichexiao',
  'form_icon_yibohui'
]);
const stateTexts = ref(['办理中', '已办结', '已撤销', '已驳回', '已归档', '已废弃', '已拒绝']);

// ------------------------ 批量操作 ---------------------------
// const batchBtnsArr = ref([
//   { btnName: '批量删除', svgName: 'btn_icon_delete', className: 'btn-icon-delete' },
//   { btnName: '批量下载', svgName: 'btn_icon_download', className: 'btn-icon-download' },
//   { btnName: '批量归档', svgName: 'btn_icon_save', className: 'btn-icon-save' }
// ]);
// // const hasSelected = computed(() => selectedRowKeys.value.length > 0);
// const selectedRowKeys = ref([]);
// function onSelectChange(selectedKeys) {
//   console.log('onSelectChange:', selectedKeys);
//   selectedRowKeys.value = selectedKeys;
// }
// function batchBtnClick(btnIndex) {
//   if (selectedRowKeys.value.length === 0) return;
//   if (btnIndex === 0) {
//     console.log('批量删除');
//   } else if (btnIndex === 1) {
//     console.log('批量下载');
//   } else {
//     console.log('批量归档');
//   }
// }
// // const emit = defineEmits([
// //   'Dismiss',
// //   'doReceiveAndCheck',
// //   'doReceiveDoc',
// //   'doDownloadFile',
// //   'doPreviewFile'
// // ]);

// // function receiveAndCheck() {
// //   emit('doReceiveAndCheck', '');
// // }

// ------------------------ 批量操作 ---------------------------
const operationDocId = ref('');
const router = useRouter();
function gotoDetail(key) {
  // console.log('详情页:', key);
  router.push({
    name: 'examinePage',
    query: {
      processInstanceId: key.processInstanceId,
      documentTitle: key.documentTitle,
      ids: key.id,
      type: 'toArchived'
    }
  });
}
const optionBtns = ref(localStorage.getItem('待归档'));
// console.log(optionBtns.value);
// 删除
const showDeleteRecordModal = ref(false);
const deleteRecordOptions = ref({
  title: '提示',
  content: '是否确定删除？删除后数据不可恢复',
  type: 1,
  onOk: () => {
    showDeleteRecordModal.value = false;
    deleteRecordById();
  },
  onCancel: () => {
    showDeleteRecordModal.value = false;
  }
});

function deleteRecord(ids) {
  operationDocId.value = ids;
  showDeleteRecordModal.value = true;
  // console.log('删除记录:', ids);
}
function deleteRecordById() {
  isLoading.value = true;
  let params = {
    id: operationDocId.value
  };
  // console.log('删除记录params', params);
  Interface.DocumentToDelete(params)
    .then(res => {
      // console.log('删除记录res：', res);
      if (res.code === 200) {
        message.success('删除成功');
        getDataList();
      } else {
        message.error(res.msg);
      }
    })
    .finally(() => {
      isLoading.value = false;
    });
}
// 废弃
const showDiscardRecordModal = ref(false);
function discardRecord(ids) {
  operationDocId.value = ids;
  showDiscardRecordModal.value = true;
  // console.log('废弃:', ids);
}
function discardModalDismiss() {
  showDiscardRecordModal.value = false;
}
function discardModalMakeSure(suggestion) {
  discardModalDismiss();
  isLoading.value = true;
  let params = {
    // processStatus: '5',
    reason: suggestion,
    processInstanceId: operationDocId.value
  };
  Interface.DocumentToAbandon(params)
    .then(res => {
      // console.log('DocumentToAbandon', res);
      if (res.code === 200) {
        message.success('操作成功');
        getDataList();
      } else {
        message.error(res.msg);
      }
    })
    .finally(() => {
      isLoading.value = false;
    });
}

// 归档
const archivedLabelArr = ref([]);

const showArchivedModal = ref(false);
function showModal(ids) {
  operationDocId.value = ids;
  showArchivedModal.value = true;
}
function archivedModalDismiss() {
  showArchivedModal.value = false;
}

function archivedModalMakeSure(tagId) {
  archivedModalDismiss();
  isLoading.value = true;
  let params = {
    labelId: tagId,
    documentIds: operationDocId.value
  };
  // console.log('params', params);
  Interface.DocumentToArchive(params)
    .then(res => {
      // console.log('DocumentToArchive', res);
      if (res.code === 200) {
        message.success('归档成功');
        getDataList();
      } else {
        message.error(res.msg);
      }
    })
    .finally(() => {
      isLoading.value = false;
    });
}
function getLabels() {
  Interface.DocumentLabelListNoPage()
    .then(res => {
      // console.log('LabelList', res);
      if (res.code === 200) {
        archivedLabelArr.value = res.data;
      } else {
        message.error(res.msg);
      }
    })
    .finally(() => {
      isLoading.value = false;
    });
}

// ------------- 分页器 -------------
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
function changePageKeyUp(event) {
  if (event.key === 'Enter') {
    event.target.blur();
  }
}
function changePageBlur(event) {
  if (/[0-9]/.test(event.target.value)) {
    // 3we5 => 35
    event.target.value = event.target.value.replace(/[^0-9]/g, '');
    currentPage.value = parseInt(event.target.value);
    let maxPage = parseInt(total.value / pageSize.value + 1);
    maxPage = maxPage > 0 ? maxPage : 1;
    if (currentPage.value > maxPage) {
      currentPage.value = maxPage;
    }
    getDataList();
    // 切换页数
  } else {
    event.target.value = '';
  }
}
function onPageChange(page, size) {
  // console.log(page, size);
  currentPage.value = page;
  pageSize.value = size;
  getDataList();
}

const dataSource = ref([]);

function getDataList() {
  isLoading.value = true;
  let params = {
    current: currentPage.value,
    size: pageSize.value,
    data: {}
  };
  if (stateValue.value && stateValue.value.length > 0 && stateValue.value !== 'all') {
    params.data.processStatus = stateValue.value;
  }
  if (keyword.value.length > 0) {
    if (searchTitle.value === 'title') {
      params.data.documentTitle = keyword.value;
    } else if (searchTitle.value === 'number') {
      params.data.documentNum = keyword.value;
    } else if (searchTitle.value === 'handler') {
      params.data.handler = keyword.value;
    }
  }
  if (beginTime.value.length > 0) {
    params.data.beginTime = changeData(beginTime.value);
  }
  if (endTime.value.length > 0) {
    params.data.endTime = changeData(endTime.value);
  }

  // console.log('params', params);
  Interface.GetDocumentLibraryList(params)
    .then(res => {
      // console.log('GetDocumentLibraryList：手动改收文', res);
      if (res.code === 200) {
        dataSource.value = res.data.records;
        dataSource.value.forEach(element => {
          // element.createTime = changeData(element.createTime / 1000);
          element.documentType = '收文';
        });
        total.value = res.data.total;
      } else {
        message.error(res.msg);
      }
    })
    .finally(() => {
      isLoading.value = false;
    });
}

onMounted(() => {
  getLabels();
  getDataList();
});
onUpdated(() => {});
let color = ref(store.state.user.setPrimaryColor);
</script>
<style lang="less" scoped>
@import './index.less';
.operation-normal {
  color: v-bind('color') !important;
  &:hover {
    cursor: pointer;
    color: rgba(0, 0, 0, 0.4);
  }
}
.operation-normals {
  cursor: pointer;
  color: rgba(0, 0, 0, 0.4);
}
</style>
